﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace BeyCooEvent.Layouts.BeyCooEvent
{
    public partial class BeyCooSettings2 : LayoutsPageBase
    {
        private string customerKey;
        public string selectedList;
        public string selectedSourceColumn;
        public Guid selectedListGUID;
        private SPWeb web = SPContext.Current.Web;
        private char sep = '#';
        public string beyCooPicUrl;
        public string selectedIndexDdlSource;
        public SPList currentList;
        public string currentListTyp;
        public HtmlTable settingsTable = new HtmlTable();
        public CheckBoxList settingsList = new CheckBoxList();

        protected override void OnLoad(EventArgs e)
        {
            ///////
            //debug:clear settings
            //if (web.Properties.ContainsKey("beycoo library")) { web.Properties["beycoo library"] = null; }
            //if (web.Properties.ContainsKey("beycoo library 2")) { web.Properties["beycoo library 2"] = null; }
            //if (web.Properties.ContainsKey("beycoo string list")) { web.Properties["beycoo string list"] = null; }
            //if (web.Properties.ContainsKey("announcements")) { web.Properties["announcements"] = null; }
            //web.AllowUnsafeUpdates = true;
            //web.Properties.Update();
            //web.AllowUnsafeUpdates = false;
            ///////
            beyCooPicUrl =   SPContext.Current.Web.Url + "/_layouts/images/BeyCooEvent/beyCoo_posterous_logo2.jpg";
            base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {
            //event handler save button for customerkey init
            saveKeyButton.Click += new EventHandler(saveKeyButton_Click);

            //init check if customerkey was already saved, when yes: load it into text box
            if (web.Properties.ContainsKey("beyCooCustomerKey"))
            {
                textboxCustomerKey.Text = web.Properties["beyCooCustomerKey"].ToString();
            }

            //initialize and load dropdown list containing splist objects for this sitecollection
            ddlSiteLists.AutoPostBack = true;
            foreach (SPList list in web.Lists)
            {
                ddlSiteLists.Items.Add(new ListItem(list.Title.ToString(), list.ID.ToString()));
            }
            //set eventhandler for dropdown list
            //ddlSiteLists.Load += new EventHandler(ddlSiteLists_Load);
            ddlSiteLists.SelectedIndexChanged += new EventHandler(ddlSiteLists_Load);
            //put value of selected dropdown list item in selectedList, should be entry [0]

            selectedList = ddlSiteLists.SelectedItem.Text;
            selectedListGUID = new Guid(ddlSiteLists.SelectedItem.Value);
            currentList = web.Lists.GetList(selectedListGUID, false);
            if (!(currentList is SPDocumentLibrary))
            {

                //fill ddlSource with available columns for beyCoo
                foreach (SPField fld in currentList.Fields)
                {
                    if (fld.CanBeDisplayedInEditForm == true)
                    {
                        ddlSource.Items.Add(new ListItem(fld.StaticName, fld.InternalName));
                    }
                }
            }
            if (ddlSource.Items.Count > 0)
            {
                selectedSourceColumn = ddlSource.SelectedItem.Text;
            }

            //init values for checkbox beyCooActive, mapping and ddlSource for the selected list
            if (web.Properties.ContainsKey(selectedList))
            {
                string[] values = web.Properties[selectedList].Split(sep);
                checkboxBeyCooActive.Checked = Boolean.Parse(values[0]);
                
                selectedIndexDdlSource = values[1];
                ddlSource.SelectedValue = selectedIndexDdlSource;
                textboxMapping.Text = values[2];
            }
            currentListTyp = currentList.GetType().ToString();
            labelTyp.Text = currentListTyp;


            //set event handler for button SaveSettingsForList
            buttonSaveSettingsForList.Click += new EventHandler(event_valueschanged);
            buttonSaveSettingsForList.Text = "Save";

            //set event handler for button DeleteSettingsForList
            buttonDeleteSettingsForList.Click += new EventHandler(buttonDeleteSettingsForList_Click);
            buttonDeleteSettingsForList.Text = "Delete";

            //fill table with lists that already have settings
            settingsTable = createTable();
            //settingsList = createList();
            PlaceHolder1.Controls.Clear();
            PlaceHolder1.Controls.Add(settingsTable);
            //PlaceHolder2.Controls.Clear();
            //PlaceHolder2.Controls.Add(settingsList);
            

            //base.CreateChildControls();
        }

        void buttonDeleteSettingsForList_Click(object sender, EventArgs e)
        {
            selectedList = ddlSiteLists.SelectedItem.Text;
            if (web.Properties.ContainsKey(selectedList))
            {
                web.Properties[selectedList] = null;
            }
            else 
            {
                //todo: popup: selected item does not have any settings stored
            }
            web.AllowUnsafeUpdates = true;
            web.Properties.Update();
            web.AllowUnsafeUpdates = false;

            //fill table with lists that already have settings
            settingsTable = createTable();
            PlaceHolder1.Controls.Clear();
            PlaceHolder1.Controls.Add(settingsTable);
        }

        //private CheckBoxList createList()
        //{
        //    CheckBoxList cbl = new CheckBoxList();
        //    foreach (SPList list in web.Lists)
        //    {
        //        string listname = list.Title;
        //        if (web.Properties.ContainsKey(listname) && !(listname.ToLower().Equals("taxonomyhiddenlist")))
        //        {
        //            string[] values = web.Properties[listname].Split(sep);
        //            cbl.Items.Add(new ListItem(listname + " - " + values[0] + " - " + values[1] + " - " + values[2]));
        //        }
        //    }
        //    return cbl;
        //}

        private HtmlTable createTable()
        {
            HtmlTable table = new HtmlTable();
            HtmlTableRow titlerow = new HtmlTableRow();
            HtmlTableCell titlename = new HtmlTableCell();
            HtmlTableCell titletyp = new HtmlTableCell();
            HtmlTableCell titleactive = new HtmlTableCell();
            HtmlTableCell titlesource = new HtmlTableCell();
            HtmlTableCell titlemapping = new HtmlTableCell();
            titlename.InnerHtml = "<strong>List/Library:</strong>";
            titlename.Width = "160";
            titletyp.InnerHtml = "<strong>Type:</strong>";
            titletyp.Width = "160";
            titleactive.InnerHtml = "<strong>beyCoo is activated:</strong>";
            titleactive.Width = "50";
            titlesource.InnerHtml = "<strong>Source for beyCoo</strong>";
            titlesource.Width = "100";
            titlemapping.InnerHtml = "<strong>Mapping:</strong>";
            titlemapping.Width = "200";
            titlerow.Cells.Add(titlename);
            titlerow.Cells.Add(titletyp);
            titlerow.Cells.Add(titleactive);
            titlerow.Cells.Add(titlesource);
            titlerow.Cells.Add(titlemapping);
            table.Rows.Add(titlerow);

            foreach(SPList list in web.Lists)
            {
                string listname = list.Title;
                if(web.Properties.ContainsKey(listname) && !(listname.ToLower().Equals("taxonomyhiddenlist")))
                {
                    if (web.Properties[listname] != null)
                    {
                        HtmlTableRow row = new HtmlTableRow();
                        HtmlTableCell name = new HtmlTableCell();
                        //name.Width = "200";
                        HtmlTableCell typ = new HtmlTableCell();
                        //typ.Width = "100";
                        HtmlTableCell active = new HtmlTableCell();
                        //active.Width = "50";
                        HtmlTableCell source = new HtmlTableCell();
                        //source.Width = "100";
                        HtmlTableCell mapping = new HtmlTableCell();
                        //mapping.Width = "200";
                        //HtmlTableCell delete = new HtmlTableCell();
                        //delete.Width = "15";
                        //Button delbtn = new Button();
                        //delete.Controls.Add(delbtn);
                        //delbtn.Text = "Del";
                        //delbtn.Click += new EventHandler(delbtn_Click);
                        string[] values = web.Properties[listname].Split(sep);
                        name.InnerText = listname;
                        typ.InnerText = currentListTyp;
                        active.InnerText = values[0];
                        source.InnerText = values[1];
                        mapping.InnerText = values[2];

                        row.Cells.Add(name);
                        row.Cells.Add(typ);
                        row.Cells.Add(active);
                        row.Cells.Add(source);
                        row.Cells.Add(mapping);
                        //row.Cells.Add(delete);

                        table.Rows.Add(row);

                        table.CellPadding = 10; 
                    }
                }
            }
            return table;
        }


        void event_valueschanged(object sender, EventArgs e)
        {

            selectedList = ddlSiteLists.SelectedItem.Text;
            selectedListGUID = new Guid(ddlSiteLists.SelectedItem.Value);
            currentList = web.Lists.GetList(selectedListGUID, false);
            currentListTyp = currentList.GetType().ToString();
            if (ddlSource.Items.Count > 0)
            {
                selectedSourceColumn = ddlSource.SelectedItem.Text;
            }
            else 
            { selectedSourceColumn = ""; }
            
            setSetting(selectedList, checkboxBeyCooActive.Checked.ToString() + sep + selectedSourceColumn + sep + textboxMapping.Text, web);

            labelTyp.Text = currentListTyp;

            //fill table with lists that already have settings
            settingsTable = createTable();
            PlaceHolder1.Controls.Clear();
            PlaceHolder1.Controls.Add(settingsTable);
        }

        void ddlSiteLists_Load(object sender, EventArgs e)
        {

            selectedList = ddlSiteLists.SelectedItem.Text;
            selectedListGUID = new Guid(ddlSiteLists.SelectedItem.Value);
            currentList = web.Lists.GetList(selectedListGUID, false);
            currentListTyp = currentList.GetType().ToString();
            ddlSource.Items.Clear();
            if (!(currentList is SPDocumentLibrary))
            {

                //fill ddlSource with available columns for beyCoo
                foreach (SPField fld in currentList.Fields)
                {
                    if (fld.CanBeDisplayedInEditForm == true)
                    {
                        ddlSource.Items.Add(new ListItem(fld.StaticName, fld.InternalName));
                    }
                }
            }

           
            //load saved setting for list from web.properties
            if (web.Properties.ContainsKey(selectedList))
            {
                string[] values = web.Properties[selectedList].Split(sep);
                labelTyp.Text = currentListTyp;
                checkboxBeyCooActive.Checked = Boolean.Parse(values[0]);  
                selectedIndexDdlSource = values[1];
                if (ddlSource.Items.Count > 0)
                {
                    ddlSource.SelectedValue = selectedIndexDdlSource;
                }
                textboxMapping.Text = values[2];
            }
            else
            {
                labelTyp.Text = currentListTyp;
                checkboxBeyCooActive.Checked = false;
                textboxMapping.Text ="";
                //checkboxCreateColumns.Checked = false;
            }

        }

        void saveKeyButton_Click(object sender, EventArgs e)
        {
            //TODO: testen was passiert wenn key geändert wird, neue key soll gespeichert werden
            //get settings from the front end and save them to the propertybag
            
            customerKey = textboxCustomerKey.Text;
            setSetting("beyCooCustomerKey", customerKey, web);

        }


        private void setSetting(string key, string value, SPWeb web)
        {
            if (!web.Properties.ContainsKey(key))
            {
                web.Properties.Add(key, value);
            }
            else
            {
                web.Properties[key] = value;
            }
            web.Properties.Update();
        }


        

    }
}
